package org.spring.springboot.controller;

import org.json.JSONArray;
import org.json.JSONObject;
import org.spring.springboot.domain.GraphFile;
import org.spring.springboot.domain.ShareFile;
import org.spring.springboot.domain.User;
import org.spring.springboot.service.IShareFileSvc;
import org.spring.springboot.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/share")
public class ShareController {

    @Autowired
    private IShareFileSvc shareFileSvc;

    @Autowired
    private IUserService userSvc;


    @PostMapping("/getAll")
    public List<Object> getAll(@RequestBody Map<String, Object> jsonMap) {
        JSONObject jsonObject = new JSONObject(jsonMap);
        String userid = jsonObject.getString("userid");

        List<GraphFile> list= shareFileSvc.selectAll(userid);
        System.out.println(list.size());

        JSONArray arr = new JSONArray();
        for (GraphFile p:list) {
            JSONObject obj = p.toJson();
            arr.put(obj);
        }
        return arr.toList();
    }

    @PostMapping("/shareGraph")
    public String shareGraph(@RequestBody Map<String, Object> jsonMap) {
        JSONObject jsonObject = new JSONObject(jsonMap);
        String sharePhoneNum = jsonObject.getString("phoneNum");
        User user = userSvc.selectOne(sharePhoneNum);
        if (user == null){
            return "failed";
        }

        String gid = jsonObject.getString("gid");
        ShareFile fileObj = new ShareFile();
        fileObj.setGid(gid);
        fileObj.setId(UUID.randomUUID().toString());
        fileObj.setOwneruid(jsonObject.getString("owneruid"));
        fileObj.setShareuid(user.getUserid());

        fileObj.setSharetime(new Date());
        shareFileSvc.save(fileObj);

        return "success";
    }



    @PostMapping("/cancel")
    public String cancel(@RequestBody Map<String, Object> jsonMap) {
        JSONObject jsonObject = new JSONObject(jsonMap);
        String gid = jsonObject.getString("gid");
        String userid = jsonObject.getString("userid");
        shareFileSvc.delete(gid,userid);
        String ret = "success";
        return ret;
    }

}
